{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e24abc10",
   "metadata": {},
   "source": [
    "# Measuring a 4-Port With The 1.5-Port NanoVNA V2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eb429f2d",
   "metadata": {},
   "source": [
    "The NanoVNA V2 is a 1.5-port VNA, meaning it can only measure the forward reflection and transmission coefficients $S_{11}$ and $S_{21}$ with its two ports. This is known as a three-receiver VNA architecture, still, fully-calibrated two-port measurements are possible despite this limitation. We recommend the readers to read [Calibration With Three Receivers](./Calibration With Three Receivers.ipynb) first to familiarize themselves with the basic background.\n",
    "\n",
    "In short, to measure the reverse coefficients $S_{12}$ and $S_{22}$ of a 2-port, it needs to be measured a second time with the port orientation physically flipped (or fake-flipped), as explained in [this example](TwoPortOnePath, EnhancedResponse, and FakeFlip.ipynb). The issue gets worse if the device under test (DUT) has even more ports, as described in [this example](./Measuring a Mutiport Device with a 2-Port Network Analyzer.ipynb).\n",
    "\n",
    "In this example, a [4-port SMA power splitter](https://www.minicircuits.com/WebStore/dashboard.html?model=ZX10Q-2-19-S%2B) is measured with a NanoVNA V2 using the Matched Port technique. It involves measuring the 4-port in all port combinations (12 measurements) with the unused ports terminated with a 50-Ohm match. For the VNA calibration, four more measurements with the SMA calibration standards are required (SHORT, OPEN, MATCH, THROUGH). The manufacturer of the DUT provides measured S-parameters on their website, which will later be used for comparison."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "78b35630",
   "metadata": {},
   "source": [
    "## Data Acquisition"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1938ba9",
   "metadata": {},
   "source": [
    "To use scikit-rf's 2-port calibration classes, such as `TwoPortOnePath`, the individual measurement results of the DUT and of the calibration standards need to be provided as 2-port networks holding the data as $S_{11}$ and $S_{21}$. The following code snippet can be used to configure the NanoVNA, and acquire and save the data:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6ce73daa",
   "metadata": {},
   "source": [
    "```python\n",
    "import skrf\n",
    "from skrf.vi.vna.nanovna import NanoVNAv2\n",
    "\n",
    "# connect to NanoVNA on /dev/ttyACM0 (Linux)\n",
    "nanovna = NanoVNAv2('ASRL/dev/ttyACM0::INSTR')\n",
    "\n",
    "# for Windows users: ASRL1 for COM1\n",
    "# nanovna = NanoVNAv2('ASRL1::INSTR')\n",
    "\n",
    "# configure frequency sweep (for example 1 MHz to 4.4 GHz in 1 MHz steps)\n",
    "f_start = 1e6\n",
    "f_stop = 4.4e9\n",
    "f_step = 1e6\n",
    "num = int(1 + (f_stop - f_start) / f_step)\n",
    "nanovna.frequency = skrf.Frequency(start=f_start, stop=f_stop, npoints=num)\n",
    "\n",
    "# measure all 12 combinations of the 4-port\n",
    "n_ports = 4\n",
    "for i_src in range(n_ports):\n",
    "    for i_sink in range(n_ports):\n",
    "        if i_sink != i_src:\n",
    "            input('Connect vna_p1 -> dut_p{}, vna_p2 -> dut_p{} and press ENTER:'.format(i_src + 1, i_sink + 1))\n",
    "            nw_raw = nanovna.get_snp_network(ports=(1, 2))\n",
    "            nw_raw.write_touchstone('./data_MiniCircuits_splitter/dut_raw_{}{}'.format(i_sink + 1, i_src + 1))\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "725ffb40",
   "metadata": {},
   "source": "The calibration standards should be measured with the same repeated calls of `get_snp_network(ports=(1, 2))` and `write_touchstone()`."
  },
  {
   "cell_type": "markdown",
   "id": "1a9d402c",
   "metadata": {},
   "source": [
    "## Offline Calibration Using `TwoPortOnePath`"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1c80d941",
   "metadata": {},
   "source": [
    "The measured data transferred from the NanoVNA via USB is always raw (uncalibrated), regardless of any calibration performed on the NanoVNA itself. This requires the correction of the data using an offline calibration. With the measurements of the calibration standards stored as individual 2-ports, a TwoPortOnePath calibration is easily created using scikit-rf. In this example, the impedances and phase delays of the measured SHORT, OPEN, MATCH, and THROUGH are assumed to be ideal, i.e. without any loss or offset:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7e12eeb1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import skrf\n",
    "from skrf.calibration import TwoPortOnePath\n",
    "\n",
    "# load networks of the raw calibration standard measurements\n",
    "short_raw = skrf.Network('./data_MiniCircuits_splitter/cal_short_raw.s2p')\n",
    "open_raw = skrf.Network('./data_MiniCircuits_splitter/cal_open_raw.s2p')\n",
    "match_raw = skrf.Network('./data_MiniCircuits_splitter/cal_match_raw.s2p')\n",
    "thru_raw = skrf.Network('./data_MiniCircuits_splitter/cal_thru_raw.s2p')\n",
    "\n",
    "# create an ideal 50-Ohm line for the short, open, match and through reference responses (\"ideals\")\n",
    "line = skrf.DefinedGammaZ0(frequency=short_raw.frequency, z0=50)\n",
    "\n",
    "# create and run the calibration\n",
    "cal = TwoPortOnePath(ideals=[line.short(nports=2), line.open(nports=2), line.match(nports=2), line.thru()],\n",
    "                     measured=[short_raw, open_raw, match_raw, thru_raw],\n",
    "                     n_thrus=1, source_port=1)\n",
    "cal.run()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "88f1fbd8",
   "metadata": {},
   "source": [
    "The 12 individual 2-port subnetworks can now be corrected with this calibration. For a full correction, the subnetworks with the forward and reverse measurements need to be provided in pairs, for example ($S_{32}$, $S_{22}$) paired with ($S_{23}$, $S_{33}$). A nested loop can take care of this. For the comparison with the measurements provided by the manufacturer, it is convenient to store the calibrated results in a single 4-port network, which can then easily be plotted:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0c62d1a8",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "# create an empty array (f x 4 x 4) for the 4-port to be filled\n",
    "s = np.zeros((len(short_raw.frequency), 4, 4), dtype=complex)\n",
    "splitter_cal = skrf.Network(frequency=short_raw.frequency, s=s)\n",
    "\n",
    "# loop through all 12 measurements, apply the calibration and save it inside 4-port network\n",
    "for i_src in range(4):\n",
    "    for i_recv in range(4):\n",
    "        if i_src != i_recv:\n",
    "            dut_raw_fwd = skrf.Network(f'./data_MiniCircuits_splitter/dut_raw_{i_recv + 1}{i_src + 1}.s2p')\n",
    "            dut_raw_rev = skrf.Network(f'./data_MiniCircuits_splitter/dut_raw_{i_src + 1}{i_recv + 1}.s2p')\n",
    "            dut_cal = cal.apply_cal((dut_raw_fwd, dut_raw_rev))\n",
    "\n",
    "            # dut_cal is now a fully populated and corrected 2-port; save it in splitter_cal\n",
    "            splitter_cal.s[:, i_src, i_src] = dut_cal.s[:, 0, 0]\n",
    "            splitter_cal.s[:, i_recv, i_src] = dut_cal.s[:, 1, 0]\n",
    "            splitter_cal.s[:, i_src, i_recv] = dut_cal.s[:, 0, 1]\n",
    "            splitter_cal.s[:, i_recv, i_recv] = dut_cal.s[:, 1, 1]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "693e34b9",
   "metadata": {},
   "source": [
    "The results are now corrected and assembled as a single 4-port network. For comparison, the magnitudes are plotted together with the measurements provided by the manufacturer:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2ef90e82",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as mplt\n",
    "\n",
    "# load reference results by MiniCircuits\n",
    "splitter_mc = skrf.Network('./data_MiniCircuits_splitter/MiniCircuits_ZX10Q-2-19-S+___Plus25degC.s4p')\n",
    "\n",
    "# plot both results\n",
    "fig, ax = mplt.subplots(4, 4)\n",
    "fig.set_size_inches(12, 8)\n",
    "\n",
    "for i in range(4):\n",
    "    for j in range(4):\n",
    "        splitter_cal.plot_s_db(i, j, ax=ax[i][j])\n",
    "        splitter_mc.plot_s_db(i, j, ax=ax[i][j])\n",
    "        ax[i][j].get_legend().remove()\n",
    "        ax[i][j].set_xlim(0, 4.4e9)\n",
    "fig.legend(['NanoVNA_cal', 'Manufacturer'], loc='upper center', ncol=2)\n",
    "fig.tight_layout(rect=(0, 0, 1, 0.95))\n",
    "mplt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c08d4e05",
   "metadata": {},
   "source": [
    "The calibrated results are pretty close to those from the manufacturer. They apparently used a Keysight N5242A PNA-X (26.5 GHz 4-port VNA) for that measurement. Given the $200 NanoVNA V2 and the sketchy assumptions made for the Matched Port technique (the termination of the unused ports of the DUT have certainly not been entirely free of any reflections), these results are not too bad."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
